package com.lstimeline.statuschecker;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import org.htmlparser.Parser;
import org.htmlparser.filters.RegexFilter;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

import com.lstimeline.utility.Validation;


public class ColumbiaLogic extends AbstractStatusChecker {
	//private static final int WORD_LIMIT = 47;
	private String urlString = "https://www-app.law.columbia.edu/webportal/preprocess/login.act";
	
	protected String getLogonString(String username, String password) throws ParserException, UnsupportedEncodingException {
		StringBuilder builder = new StringBuilder();
		queryBuilder(builder, "username", username);
		queryBuilder(builder, "password", password);
		// remove the last '&'
		builder.deleteCharAt(builder.length() - 1);
		
		return builder.toString();
	}
	
	//My Columbia Law
	//Post logon information to https://www-app.law.columbia.edu/webportal/preprocess/login.act
	protected void logon(String username, String password) throws Exception{
		String logonString = getLogonString(username, password);
		setupPOSTConnection(urlString, logonString.length());
		
		// post the login query
		// Username, Password
		// No redirection
		PrintWriter out = new PrintWriter(conn.getOutputStream());
		out.write(logonString);
		out.flush();
		out.close();
		
		//Important: to ignore response so that the connection can be recylcled.
		conn.getInputStream().close();
		
		//GET JSESSIONID, Path
		receiveCookies();
	}
	
	private NodeList retrieve() throws Exception{
		urlString = "https://www-app.law.columbia.edu/webportal/process/checkStatus.act";
		
		setupGETConnection(urlString);
		
		parser = new Parser(conn);
		NodeList nodes = parser.parse(
				new RegexFilter("^(Application Status:)[a-zA-Z\\s]+")
		);
		
		return nodes;
	}
	
	private void logoff() throws Exception {
		urlString = "https://www-app.law.columbia.edu/webportal/process/logout.act";
		setupGETConnection(urlString);
		conn.connect();
		conn.getInputStream().close();
	}
	
	public String getStatusMessage(String username, String password) {
		//loosely sanitize username and password
		if(!Validation.isGeneralLoginWellFormed(username, password)) {
			statusCode = AUTH_FAIL;
			return null;
		}
		
		NodeList nodes = null;
		try {
			logon(username, password);
			
			nodes = retrieve();
			
			if(nodes == null || nodes.size() == 0) {
				statusCode = AUTH_FAIL;
				return null;
			} else {
				statusCode = SUCCESS;
				logoff(); //confirmed to work
				String statusText = nodes.elementAt(0).toPlainTextString();
				String[] temp = statusText.split(":");
				return temp[1].trim();
			}
		} catch (Exception e) {
			statusCode = ERR;
			e.printStackTrace();
			return null;
		}
	}

}
